package com.findsing.jetty.websocket.server.endpoint;

import static com.findsing.jetty.websocket.server.endpoint.BaseEndpoint.sessions;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;

import org.apache.log4j.Logger;
import org.eclipse.jetty.server.session.SessionHandler;
import org.springframework.beans.factory.annotation.Autowired;

public class BaseEndpoint {
	private static final Logger logger = Logger.getLogger(BaseEndpoint.class);
	protected static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
	
	@Autowired
	SessionHandler sessionHandler;
	private HttpSession httpSession;
	
	public HttpSession getHttpSession(String sessionId) {
		httpSession=sessionHandler.getSessionManager().getHttpSession(sessionId);
		return httpSession;
	}

	public void onOpen(final Session session, EndpointConfig config) {
		sessions.add(session);
		/**
		 * Doesn't work, SpringServerEndpointConfigurator will not send HttpSession here
		 * as is not safe this time.
		 */
		httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
	}
	
	public void onClose(final Session session) {
		sessions.remove(session);
	}
}
